package com.kuhyygy.activity;

import java.io.IOException;
import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.kuhyygy.R;
import com.kuhyygy.adapter.ListViewAdapter;

import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ListView;

public class LoadingActivity extends ListActivity implements OnScrollListener {
	
	private static final String tag = "LoadingActivity";

	private ListView listView;
	private int visibleLastIndex = 0; // 最后的可视项索引
	private int visibleItemCount; // 当前窗口可见项总数
	private ListViewAdapter adapter;
	private View loadMoreView;
	private Button loadMoreDataButton;
	private Handler handler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);  

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());

        setContentView(R.layout.loadmoremain);  
          
        loadMoreView = getLayoutInflater().inflate(R.layout.loadmore, null);  
        loadMoreDataButton = (Button) loadMoreView.findViewById(R.id.loadMoreDataButton);  
        listView = getListView();               //获取id是list的ListView   
        listView.addFooterView(loadMoreView);   //设置列表底部视图
        initAdapter();  
        setListAdapter(adapter);                //自动为id是list的ListView设置适配器   
        listView.setOnScrollListener(this);     //添加滑动监听   
	}
	
	/** 
     * 初始化适配器 
     */  
    private void initAdapter() {  
        ArrayList<String> items = new ArrayList<String>();  
        
        
        HttpTransportSE ht = new HttpTransportSE("http://113.108.186.143:8080/KSecurity/webService/userWsService");
        //使用soap1.1协议创建Envelop对象
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        //实例化SoapObject对象
        SoapObject request = new SoapObject("http://ws.security.kuhyygy.com/", "loadUsers");
        request.addProperty("pageNo", 1);
        request.addProperty("pageSize", 10);
        envelope.bodyOut = request;
        envelope.dotNet = false;
		try {
			ht.call(null, envelope);
			SoapObject result = (SoapObject) envelope.bodyIn;
			for (int i = 0 ; i < result.getPropertyCount(); i++) {
				SoapObject so = (SoapObject) result.getProperty(i);
				SoapPrimitive pi = (SoapPrimitive) so.getProperty("name");
				SoapPrimitive piAge = (SoapPrimitive) so.getProperty("age");
				items.add(pi.getValue().toString() + "--" + piAge.getValue().toString());
			}
		} catch (HttpResponseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        adapter = new ListViewAdapter(this, items);  
    }  

    /** 
     * 滑动时被调用 
     */  
    @Override  
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {  
        this.visibleItemCount = visibleItemCount;  
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;  
    }  
  
    /** 
     * 滑动状态改变时被调用 
     */  
    @Override  
    public void onScrollStateChanged(AbsListView view, int scrollState) {  
        int itemsLastIndex = adapter.getCount() - 1;    //数据集最后一项的索引   
        int lastIndex = itemsLastIndex + 1;             //加上底部的loadMoreView项   
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {  
            //如果是自动加载,可以在这里放置异步加载数据的代码   
            Log.i("LOADMORE", "loading...");  
        }
    }
    
    
	
	/**
	 * 点击按钮事件
	 * 
	 * @param view
	 */
	public void loadMore(View view) {
		loadMoreDataButton.setText("loading..."); // 设置按钮文字loading
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				loadData();
				adapter.notifyDataSetChanged(); // 数据集变化后,通知adapter
				listView.setSelection(visibleLastIndex - visibleItemCount + 1); // 设置选中项
				loadMoreDataButton.setText("load more"); // 恢复按钮文字
			}
		}, 2000);
	}

	/**
	 * 模拟加载数据
	 */
	private void loadData() {
		int count = adapter.getCount();
		for (int i = count; i < count + 10; i++) {
			adapter.addItem(String.valueOf(i + 1));
		}
	}

}
